package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.*;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.TraveComment;
import cn.wolfcode.wolf2w.query.TravelQueryObject;
import cn.wolfcode.wolf2w.redis.service.IRedisService;
import cn.wolfcode.wolf2w.redis.test.RedisByKey;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.*;
import cn.wolfcode.wolf2w.util.DBHelper;
import cn.wolfcode.wolf2w.util.TravelStatisVO;
import cn.wolfcode.wolf2w.util.TravelStateAndPublicUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository travelRepository;
    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private MongoTemplate template;
    @Autowired
    private IDestinationService destinationService;
    @Autowired
    private StringRedisTemplate template1;
    @Autowired
    private ITravelService travelService;

    @Override
    public void insert(Travel travel) {
        travel.setId(null);
        travelRepository.insert(travel);
    }

    @Override
    public void delete(String id) {
        travelRepository.deleteById(id);
    }

    @Override
    public void update(Travel travel) {
        travelRepository.save(travel);
    }

    @Override
    public Travel selectOne(String id) {
        Travel travel = travelRepository.findById(id).orElse(null);
        String userId = travel.getUserId();
        UserInfo userInfo = userInfoService.selectOne(userId);
        travel.setAuthor(userInfo);
        travel.setDest(destinationService.selectOne(travel.getDestId()));

        //Travel travel = byId.get();
        return travel;
    }

    @Override
    public List<Travel> selectAll() {
        List<Travel> all = travelRepository.findAll();
        return all;
    }

    //@Override
    //public List<Travel> getDestByRegionId(String rid) {
    //    //1、通过区域id查询区域对象
    //    Region region = regionService.selectOne(rid);
    //    //2、从区域对象上获取目的地id的集合
    //    List<String> refIds = region.getRefIds();
    //    //3、将目的地id的集合转换成目的地名称的集合
    //    List<Travel> travels = travelRepository.findByIdIn(refIds);
    //    return travels;
    //}

    @Override
    public Page<Travel> query(TravelQueryObject q) {
        //1、创建查询对象
        Query query=new Query();

        //List<Travel> travels=this.selectAll();
        ////通过遍历，将当前登录用户的状态封装到查询封装类中
        //for(Travel travel:travels){
        //    int state = travel.getState();
        //    TravelStateAndPublicUtils tsp=new TravelStateAndPublicUtils();
        //    tsp.setSp(state);
        //    String id1 = travel.getId();
        //}
        ////通过遍历，将当前登录用户的是否公开封装到查询封装类中
        //for(Travel travel:travels){
        //    int isPublic = travel.getIsPublic();
        //    String id1 = travel.getId();
        //}

        //拼接游记状态，发布并且公开的游记才会显示


        ////查询出所有的游记
        //List<Travel> travels = this.selectAll();
        ////进行遍历判断是否是公开且是否是发布
        //for(Travel travel:travels){
        //    if((travel.getIsPublic()==Travel.ISPUBLIC_YES)&&(travel.getState()==Travel.STATE_RELEASE)){
        //        //若是公开且是发布，则可以进行条件的拼接
        //        String title = travel.getTitle();
        //        query.addCriteria(Criteria.where("title").is(title));
        //    }
        //}


        //拼接当前登录用户的id,若当前登录用户的id不为null的话，进行条件的拼接，若为null的话，则不拼接
        if(q.getUserId()!=null){
            query.addCriteria(Criteria.where("userId").is(q.getUserId()));
        }
        //拼接出行天数的查询条件（在拼接条件之前，需要判断将数据转成数据类对象，要判断该对象是否为空）
        TraveComment traveComment = TraveComment.DAYTYPE.get(q.getDayType());
        if(traveComment!=null){
            query.addCriteria(Criteria.where("day").gte(traveComment.getMinNum()).lte(traveComment.getMaxNum()));
        }
        //拼接人均花费的查询条件(此处的工具类对象也要判断是否为空)
        TraveComment traveComment1 = TraveComment.PEREXPENDTYPE.get(q.getPerExpendType());
        if(traveComment1!=null){
            query.addCriteria(Criteria.where("perExpend").gte(traveComment1.getMinNum()).lte(traveComment1.getMaxNum()));
        }
        Pageable pageable=null;
        if(StringUtils.hasLength(q.getDestId())){
            query.addCriteria(Criteria.where("destId").regex(q.getDestId()));//进行拼接高级查询条件时需要使用regex
        }
        //2、判断keyword是否为空，若不为空，则进行条件的拼接
        if(StringUtils.hasLength(q.getKeyword())){
            query.addCriteria(Criteria.where("name").regex(q.getKeyword()));//进行拼接高级查询条件时需要使用regex
        }
        //判断父亲id长度是否为空，若为空，拼接成null
        if(!StringUtils.hasLength(q.getParentId())){
            query.addCriteria(Criteria.where("parentId").is(null));
        }else{
            query.addCriteria(Criteria.where("parentId").is(q.getParentId()));
        }
        //3、添加分页语句
        //排序条件的拼接
        if(q.getOrderType()==1){
             pageable=PageRequest.of(q.getCurrentPage()-1, q.getPageSize(), Sort.Direction.DESC,"replynum");
        }else if(q.getOrderType()==2) {
            pageable = PageRequest.of(q.getCurrentPage()-1, q.getPageSize(), Sort.Direction.DESC, "releaseTime");
        }else{
            pageable = PageRequest.of(q.getCurrentPage()-1, q.getPageSize(), Sort.Direction.DESC, "_id");
        }
        Page<Travel> page = DBHelper.query(q,query, Travel.class, template, pageable);
        //在返回分页结果前，给游记作者添加信息，否则目的地游记明细页面渲染不成功
        for(Travel travel:page){
            String userId = travel.getUserId();
            UserInfo userInfo = userInfoService.selectOne(userId);
            travel.setAuthor(userInfo);
        }
        return page;
    }

    //审核处理
    @Override
    public void audit(String id, int state) {

        //判断是否满足审核条件
        Travel travel = this.selectOne(id);
        //判断游记对象是否存在以及判断该游记是否处于审核状态
        if(travel==null||Travel.STATE_WAITING!=travel.getState()){
            throw new LogicException("当前不是处于审核状态");
        }
        if(state==Travel.STATE_RELEASE){
            //审核通过
            //游记状态改为审核通过
            travel.setState(Travel.STATE_RELEASE);
            //游记发布时间改为当前时间
            travel.setReleaseTime(new Date());
            //游记最后更新时间改为当前时间
            travel.setLastUpdateTime(new Date());
        }else{
            //审核拒绝
            //将游记状态改为审核拒绝
            travel.setState(Travel.STATE_REJECT);
            //游记发布时间改为null
            travel.setReleaseTime(null);
            //游记最后更新时间改为当前时间
            travel.setLastUpdateTime(new Date());
        }
        //最后更新
        this.update(travel);

    }
    //保存或编辑
    @Override
    public void saveOrUpdate(Travel travel) {
        //进行保存之前需要对一些数据进行维护
        //目的地名称
        String destId = travel.getDestId();
        Destination destination = destinationService.selectOne(destId);
        String name = destination.getName();
        travel.setDestName(name);
        //用户id,需用redis去获取(在映射方法中进行维护)
        //最后更新是时间
        travel.setLastUpdateTime(new Date());
        if(StringUtils.hasLength(travel.getId())){

            this.update(travel);
        }else{
            //创建时间
            travel.setCreateTime(new Date());
            String userId = travel.getUserId();
            UserInfo userInfo = userInfoService.selectOne(userId);
            travel.setAuthor(userInfo);

            this.insert(travel);
        }
    }
    //通过当前登录用户的id查询出所有的游记
    @Override
    public List<Travel> queryByUserId(String id) {
        List<Travel> travels= travelRepository.queryByUserId(id);
        return travels;
    }

    //收藏数加一
    @Override
    public boolean travelId(String travelId, String id) {
        Travel travel = this.selectOne(travelId);
        TravelStatisVO vo =null;
        //用用户id拼接成key
        String key = RedisByKey.TRAVELS_USERID_FAVOR.join(id);
        //判断该key是否存在
        //若不存在
        List<String> list=new ArrayList<>();
        if(template1.hasKey(key)){
            //若存在，获取list集合
            String s = template1.opsForValue().get(key);
            //将s转换成集合类型
            list = JSON.parseArray(s, String.class);
            //判断list1中是否包含游记id
            if(list.contains(travelId)){
                //包含，返回false，将vo中的收藏字段减一，并将游记id从集合中移除
                vo = this.getTravelStatisVO(travel);
                vo.setFavornum(vo.getFavornum()-1);
                list.remove(travelId);
            }else{
                //不包含，获取vo对象，将vo中的收藏字段加一，并将游记id储存到list中区
                vo=this.getTravelStatisVO(travel);
                vo.setFavornum(vo.getFavornum()+1);
                list.add(travelId);
            }
        }
        //跟新记号
        String li = JSON.toJSONString(list);
        template1.opsForValue().set(key,li);
        //更新vo
        this.setTravelStatisVO(travel, vo);
        return list.contains(travelId);
    }

    @Override
    public TravelStatisVO getTravelStatisVO(Travel travel) {
        //将传过来的攻略id进行key的拼接
        String key = RedisByKey.TRAVEL_STATIC_VO.join(travel.getId());
        TravelStatisVO vo=new TravelStatisVO();
        //判断redis中是否还有该key，若有将key所对应的键值转成统计数据封装类的类型
        if(template1.hasKey(key)){
            String s = template1.opsForValue().get(key);
            vo = JSON.parseObject(s, TravelStatisVO.class);
        }else{

            //若redis中不含有该key，我们需要对统计的数值进行初始化
            //对vo对象的字段进行维护
            BeanUtils.copyProperties(travel, vo);
            //还需要对vo对象中的攻略id字段进行维护
            vo.setTravelId(travel.getId());
            this.setTravelStatisVO(travel, vo);
        }
        return vo;
    }


    @Override
    public void setTravelStatisVO(Travel travel,TravelStatisVO travelStatisVO) {
        ////通过攻略id拼接成key
        String key = RedisByKey.TRAVEL_STATIC_VO.join(travel.getId());
        //将该类转化成json字符串的格式
        String travelStatisVo2 = JSON.toJSONString(travelStatisVO);
        //进行更新
        template1.opsForValue().set(key, travelStatisVo2);
    }

    //通过目的地的名称查出所有的游记
    @Override
    public List<Travel> queryByDestName(String name) {
        List<Travel> travels=travelRepository.queryByDestName(name);
        for(Travel t:travels){
            String userId = t.getUserId();
            UserInfo userInfo = userInfoService.selectOne(userId);
            t.setAuthor(userInfo);
        }
        return travels;
    }
    //
    ////进行编辑回显
    //@Override
    //public Travel input(String id) {
    //    Travel travel = this.selectOne(id);
    //    String userId = travel.getUserId();
    //    UserInfo userInfo = userInfoService.selectOne(userId);
    //    travel.setAuthor(userInfo);
    //    return travel;
    //}
}
